// pages/card/index.js
var app = getApp();
const utils = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    animationData: "",
    showModalStatus: false,
    isopacity: false,
    showId: null,
    showSendMsg: false,
    blogList: [],
    imgs: null,
    id: null,
    plain: true,
    cardInfo: {},
    content: "",
    msgLength: 0,
    isSendMsg: false,
    mobile: "",
    blogListLength: 1,
    loadingMoreHidden: true,
    showTabBar: true,
    loadingMorebottom: true,
    CurrentPage: 1,
    typeId:0,//商圈id
    startDate:0,
    isAccredit: false, //是否授权
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    utils.isAccredit(function (isAccredit) {
      that.setData({
        isAccredit: isAccredit
      })
    });
  },

  //获取未读消息
  getMsgUnRead: function (stuffUId) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/WebIM/GetUnRead?uid=' + app.globalData.userInfo.Uid + "&stuffUId=" + stuffUId,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            msgLength: res.data.Data
          })
        }
      },
    })
  },

  //进入聊天页面
  formSubmit: function (e) {
    var cardInfo = this.data.cardInfo.CardInfo;
    var mobile = wx.getStorageSync("mobile");
    if (mobile) {
      // wx.navigateTo({
      //   url: '/pages/weijieke/Business/Business?seltoid=' + cardInfo.Uid + '&name=' + cardInfo.Name
      // })
      utils.toChat(cardInfo);
    }
    // var formId = e.detail.formId;
    // utils.addFormIdMsg(formId);
    utils.aiCardActionRecord(18);
  },

  //获取手机号
  getPhoneNumber: function (e) {
    let that = this;
    var cardInfo = that.data.cardInfo.CardInfo;
    // let isAccredit = that.data.isAccredit;
    utils.getMobile(e);
    utils.toChat(cardInfo);
    // if (isAccredit) {
    //   utils.toChat(cardInfo);
    //   wx.navigateTo({
    //     url: '/pages/weijieke/Business/Business?seltoid=' + cardInfo.Uid + '&name=' + cardInfo.Name
    //   })
    // }
  },

  //是否授权登陆
  toShowToast: function () {
    let back = '/pages/index/index';
    wx.navigateTo({
      url: '../accredit/index?back=' + back,
    })
  },


  preView: function (e) {
    var that = this;
    var startDate = utils.formatTime(new Date());
    var index = e.currentTarget.dataset.idx;
    var imgs = e.currentTarget.dataset.all;
    var id = e.currentTarget.dataset.id;
    that.setData({ typeId: id, startDate: startDate})
    wx.previewImage({
      current: imgs[index], // 当前显示图片的http链接
      urls: imgs            // 需要预览的图片http链接列表
    })
  },

 

  toComment: function (e) {
    let that = this;
    that.setData({ id: e.currentTarget.dataset.id, showTabBar: false })
    this.hideModal();
    this.setData({
      showSendMsg: true,
      isSendMsg: true
    })
  },
  closeMsg: function () {
    this.hideModal();
    this.setData({
      showSendMsg: false,
      isSendMsg: false,
      showTabBar: true
    })
  },


  showModal: function (e) {
    var id = e.currentTarget.dataset.id;
    // 显示遮罩层  
    if (this.data.showModalStatus && id == this.data.showId) {
      this.hideModal();
      return
    }
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.width("0rpx").step()
    animation.width("300rpx").step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true,
      showId: id
    })
    setTimeout(function () {
      animation.translateX(0).step()
      this.setData({
        animationData: animation.export(),
      })
    }.bind(this), 200)
    var that = this;
    setTimeout(function () {
      that.setData({
        isopacity: true
      })
    }.bind(this), 400)
  },
  hideModal: function () {
    // 隐藏遮罩层  
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation;
    animation.width("0rpx").step()
    this.setData({
      animationData: animation.export(),
      isopacity: false
    })
    var that = this;
    setTimeout(function () {
      animation.translateX(0).step()
      that.setData({
        animationData: animation.export(),
        showModalStatus: false,
        showId: that.data.showId
      })
    }.bind(this), 200)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   * 
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    var typeId = that.data.typeId;
    if (typeId != 0){
      utils.recordActionTime(this.data.startDate, 5, typeId)
      that.setData({ typeId:0 })
    }
    if (app.globalData.userInfo) {
      console.log("用户信息存在")
      that.getAiCardInfo();
      utils.aiCardActionRecord(5);
      that.onMyEvent(app.globalData.userInfo.Uid);
    } else {
      console.log("用户信息不存在,延时加载")
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
    var mobile = wx.getStorageSync("mobile");
    if (mobile) {
      this.setData({ mobile: mobile })
    }
  },
  // 连接socket监听聊天消息
  onMyEvent: function (uid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/IM/UserByOpenId?openId=' + uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            let fromuid = res.data.Data.Id;
            console.log('开始建立连接');
            wx.connectSocket({
              url: app.globalData.socketUrl,
              success: function (res) {
                console.log('创建一个 WebSocket 连接', res);
              },
              fail: function (err) {
                console.log('创建一个 WebSocket 连接失败', err);
              }
            })
            // 监听连接成功
            wx.onSocketOpen(function () {
              console.log('socket连接成功者', fromuid);
              let datas = { "type": "connect", "from_uid": fromuid };
              wx.sendSocketMessage({
                data: JSON.stringify(datas),
                success: function (res) {
                  console.log('发送成功', res);
                }, fail: function (err) {
                  console.log('发送失败', err);
                }
              })
            })
            // 监听 WebSocket 接受到服务器的消息
            wx.onSocketMessage(message => {
              console.log('监听 WebSocket 接受到服务器的消息事件=================', message);
              //把JSONStr转为JSON
              message = message.data.replace(" ", "");
              if (typeof message != 'object') {
                message = message.replace(/\ufeff/g, ""); //重点
                var jj = JSON.parse(message);
                message = jj;
                if (message.type == 'send' && message.content) {
                  let msgLength = that.data.msgLength;
                  wx.request({
                    url: app.globalData.host + '/api/IM/UserByOpenId?openId=' + that.data.cardInfo.CardInfo.Uid,
                    success: function (res) {
                      if (res.data.Code == 0 && res.data.Data) {
                        let fromuid = res.data.Data.Id;
                        if(message.from_uid == fromuid){
                          that.setData({
                            msgLength: msgLength + 1
                          })
                        }
                      }
                    }
                  })
                }
              }
              console.log("【websocket监听到消息】内容如下：", message);
            })
            wx.onSocketError(function (err) {
              console.log('监听 WebSocket 错误事件', err);
            });
            wx.onSocketClose(function (res) {
              console.log('WebSocket 已关闭啦啦啦！', res)
            });
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },


  // 获取名片信息
  getAiCardInfo: function () {
    var that = this;
    var cardId = wx.getStorageSync("cardId")
    if (cardId) {
      wx.request({
        url: app.globalData.host + '/api/BusinessCard/GetAiCard?uid=' + app.globalData.userInfo.Uid + '&staffId=' + cardId,
        success: function (res) {
          if (res.data.Code == 0) {
            that.setData({
              cardInfo: res.data.Data
            })
            that.getMsgUnRead(res.data.Data.CardInfo.Uid)
            that.getBlogList(res.data.Data)
          }
        },
      })
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.loadMore();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    var cardInfo = that.data.cardInfo.CardInfo;
    if (res.from === 'button') {
      return {
        title: (res.target.dataset.name).trim() + "的动态",
        path: '/pages/weijieke/shareDetail/index?id=' + res.target.dataset.id,
        imageUrl: res.target.dataset.img,
        success: function (res) {
          wx.showModal({
            title: '提示',
            content: '转发成功',
            showCancel: false
          })
          utils.aiCardActionRecord(13);
        }
      }
    } else {
      return {
        title: cardInfo.Name + "的动态",
        path: '/pages/weijieke/states/index',
        success: function (res) {
          wx.showModal({
            title: '提示',
            content: '转发成功',
            showCancel: false
          })
          utils.aiCardActionRecord(13);
        }
      }
    }
  },
  //获取微博列表
  getBlogList: function (cardInfo) {
    let that = this;
    cardInfo = cardInfo.CardInfo;
    wx.request({
      url: app.globalData.host + '/api/Blog/BlogList?storeId=' + app.globalData.storeId + '&uid=' + cardInfo.Uid + '&staffId=' + cardInfo.Id + '&PageNumber=' + that.data.CurrentPage,
      success: function (res) {
        var blogList = res.data.Data.BlogList;
        blogList.forEach(function (item, index) {
          if (item.Imgs) {
            item.Imgs = that.trim(item.Imgs).trim().split(",");
          }
        });
        for (let i = 0; i < blogList.length; i++) {
          let imglist = blogList[i].Imgs;
          for (let k = 0; k < imglist.length; k++) {
            imglist[k] = that.formatBlogImage(imglist[k]);
          }
        }
        for (let j = 0; j < blogList.length; j++){
          blogList[j].Avater = that.formatAvater(blogList[j].Avater);
        }
        if (that.data.CurrentPage != 1) {
          var preGoods = that.data.blogList
          blogList = preGoods.concat(blogList);
        }
        that.setData({ blogList: blogList, loadingMoreHidden: false, blogListLength: blogList.length, loadingMorebottom: res.data.Data.PageModel.HasNextPage });
      },
    })
  },

  loadMore: function () {
    var that = this;
    if (!that.data.loadingMorebottom) return;
    var currPage = that.data.CurrentPage;
    that.setData({
      CurrentPage: currPage + 1
    })
    that.getBlogList(that.data.cardInfo);
  },

  //路径判断
  formatBlogImage: function (logo) {
    if (logo == null || this.trim(logo) == "") return "";
    if (logo.indexOf("http") > -1) return logo;
    return 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/blog/thumb500_800/' + logo;
  },
  //路径判断
  formatAvater: function (logo) {
    if (logo == null || this.trim(logo) == "") return "";
    if (logo.indexOf("http") > -1) return logo;
    return 'https://static.711688.net.cn/upload/card/source/' + logo;
  },

  //删除左右两端的空格
  trim: function (str) {
    if (str == null) return "";
    return str.replace(/(^\s*)|(\s*$)/g, "");
  },

  //获取评论框内容
  getContent: function (e) {
    this.setData({ content: e.detail.value })
  },
  //添加评论
  addBlogComment: function () {
    var that = this;
    if (that.data.content == "") {
      wx.showToast({
        title: '内容不能为空！',
        icon: 'success',
        duration: 2000
      })
      return
    }
    wx.request({
      url: app.globalData.host + '/api/Blog/AddBlogComment?blogid=' + that.data.id + '&uid=' + app.globalData.userInfo.Uid + '&Content=' + that.data.content,
      success: function (res) {
        if (res.data.Code == 0) {
          that.closeMsg();
          that.setData({ content: "" })
          that.getBlogList(that.data.cardInfo);
        }
      },
    })
  },
  //点赞功能
  addUp: function (e) {
    let that = this;
    var id = e.currentTarget.dataset.id;
    wx.request({
      url: app.globalData.host + '/api/Blog/AddUp?blogId=' + id + '&uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.hideModal();
          that.getBlogList(that.data.cardInfo);
        }
      },
    })
  },
  //离开当前页面
  onUnload: function () {
    utils.toCloseSocket();
  },
  onHide: function () {
    utils.toCloseSocket();
  },
  //去除换行
  trim: function (e) {
    return e.replace(/[\r\n]/g, "");
  }
})